package com.cn.shuangzi.ad;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.ad.bean.ADPlatform;
import com.cn.shuangzi.ad.bean.AdShowTypeInfo;
import com.cn.shuangzi.ad.retrofit.ADHttpRequestRetrofitService;
import com.cn.shuangzi.ad.retrofit.ADRequestInterceptor;
import com.cn.shuangzi.ad.util.tt.TTAdManagerHolder;
import com.cn.shuangzi.bean.MaterialsInfo;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.retrofit.SZRetrofitResponseListener;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qq.e.comm.managers.GDTAdSdk;
import com.qq.e.comm.managers.setting.GlobalSetting;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_INTERACTION_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_NATIVE_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_SELF_BANNER_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_SELF_FLOAT_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOAD_SPLASH_POLICY;
import static com.cn.shuangzi.ad.util.ADConst.AD_LOCAL_ERROR_EVENT_ID;
import static com.cn.shuangzi.ad.util.ADConst.AD_PLATFORM_LOCAL;
import static com.cn.shuangzi.ad.util.ADConst.AD_READ_LOCAL_EVENT_ID;
import static com.cn.shuangzi.ad.util.ADConst.AD_SHOWN_COMPANY;
import static com.cn.shuangzi.ad.util.ADConst.ERROR_CODE;
import static com.cn.shuangzi.ad.util.ADConst.ERROR_MSG;
import static com.cn.shuangzi.ad.util.ADConst.TAG_SPLASH;
import static com.cn.shuangzi.retrofit.SZRetrofitManager.ERROR_NET_FAILED;

/**
 * Created by CN.
 */

public class ADManager {
    private static ADManager INSTANCE;
    private SZXmlUtil sZXmlUtil;

    private ADHttpRequestRetrofitService adHttpRequestRetrofitService;
    private static String API_SERVICE = "https://switch.api.shuangzikeji.cn:8080/";
    private String deviceId;
    private boolean isInitAd;
    private OnAdInitDoneListener onAdInitDoneListener;
    private ADManager() {
        isInitAd = false;
        if (sZXmlUtil == null) {
            sZXmlUtil = new SZXmlUtil(SZManager.getInstance().getContext(), AD_LOAD_POLICY);
        }
        deviceId = sZXmlUtil.getString("device_id");
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = SZUtil.getUUID();
            sZXmlUtil.put("device_id", deviceId);
        }
    }

    public static ADManager getInstance() {
        if (INSTANCE == null) {
            synchronized (ADManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new ADManager();
                }
            }
        }
        return INSTANCE;
    }

    public void initAd() {
        if (!isInitAd) {
            TTAdManagerHolder.isBeginInit = false;
            SZUtil.log("广告插件未初始化，开始初始化");
            isInitAd = true;
            GlobalSetting.setChannel(getGDTChannelCode());
            GDTAdSdk.init(SZApp.getInstance(), SZUtil.getGDT_APPID(SZManager.getInstance().getContext()));
            TTAdManagerHolder.init(SZApp.getInstance(), SZManager.getInstance().isDebugMode(),onAdInitDoneListener);
        }
    }

    public boolean isInitAd() {
        return isInitAd;
    }

    public void setInitAd(boolean initAd) {
        isInitAd = initAd;
    }

    public void setAdShownCompany(String company) {
        sZXmlUtil.put(AD_SHOWN_COMPANY, company);
    }

    public void removeAdShownCompany() {
        sZXmlUtil.remove(AD_SHOWN_COMPANY);
    }

    public String getAdShownCompany() {
        return sZXmlUtil.getString(AD_SHOWN_COMPANY);
    }

    public boolean isShowAd() {
        if (sZXmlUtil == null) {
            sZXmlUtil = new SZXmlUtil(SZManager.getInstance().getContext(), AD_LOAD_POLICY);
        }
        String data = sZXmlUtil.getString(AD_LOAD_SPLASH_POLICY);
        if (data != null && !data.equals("")) {
            try {
                List<ADPlatform> adPlatformList = new Gson().fromJson(data, new TypeToken<List<ADPlatform>>() {
                }.getType());
                if (adPlatformList != null && adPlatformList.size() > 0) {
                    return adPlatformList.get(0).isAdIsOpen();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public List<ADPlatform> getSplashAdList() {
        List<ADPlatform> adPlatformList = null;
        String data = sZXmlUtil.getString(AD_LOAD_SPLASH_POLICY);
        if (data != null && !data.equals("")) {
            try {
                adPlatformList = new Gson().fromJson(data, new TypeToken<List<ADPlatform>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return adPlatformList;
    }

    public AdShowTypeInfo getSplashClickEyeAdShowType() {
        List<ADPlatform> adPlatformList = getSplashAdList();
        AdShowTypeInfo adShowTypeInfo = null;
        if (SZValidatorUtil.isValidList(adPlatformList)) {
            for (ADPlatform adPlatform : adPlatformList) {
                if (adPlatform.getAdShowTypeInfo() != null && SZValidatorUtil.isValidString(adPlatform.getAdShowTypeInfo().getClickEyeMode())) {
                    adShowTypeInfo = adPlatform.getAdShowTypeInfo();
                    break;
                }
            }
        }
        return adShowTypeInfo;
    }

    public boolean isShowInteractionAd(boolean isShownClickEye) {
        AdShowTypeInfo adShowTypeInfo = getInteractionAdShowType();
        if (adShowTypeInfo != null&&adShowTypeInfo.getShowType()!=null) {
            switch (adShowTypeInfo.getShowType()){
                case AdShowTypeInfo.ALWAYS_TYPE:
                    return true;
                case AdShowTypeInfo.CLOSE_TYPE:
                    return false;
                case AdShowTypeInfo.NORMAL_TYPE:
                    return !isShownClickEye;
            }
            return !isShownClickEye;
        }
        return false;
    }
    public AdShowTypeInfo getInteractionAdShowType() {
        List<ADPlatform> adPlatformList = getInteractionAdList();
        if (SZValidatorUtil.isValidList(adPlatformList)) {
            return adPlatformList.get(0).getAdShowTypeInfo();
        }
        return null;
    }

    public static void setApiService(String apiService) {
        API_SERVICE = apiService;
    }

    public ADHttpRequestRetrofitService getADApiService() {
        if (adHttpRequestRetrofitService == null) {
            adHttpRequestRetrofitService = SZRetrofitManager.getInstance().getRetrofit(API_SERVICE, new ADRequestInterceptor()).create(ADHttpRequestRetrofitService.class);
        }
        return adHttpRequestRetrofitService;
    }

    public void getSelfAd(String channel, String packageName, String version, final OnSplashADLoadListener onSplashADLoadListener) {
        SZRetrofitManager.getInstance().request(getADApiService().getAd(channel, packageName, version, "ALL", deviceId), TAG_SPLASH, new SZRetrofitResponseListener.SimpleSZRetrofitResponseListener() {
            @Override
            public void onSuccess(String data) {
                List<ADPlatform> adPlatformList = new Gson().fromJson(data, new TypeToken<List<ADPlatform>>() {
                }.getType());
                List<ADPlatform> adSelfBannerList = new ArrayList<>();
                List<ADPlatform> adSelfFloatList = new ArrayList<>();
                if (SZValidatorUtil.isValidList(adPlatformList)) {
                    for (ADPlatform adPlatform : adPlatformList) {
                        switch (adPlatform.getAdType()) {
                            case ADPlatform.AD_TYPE_BANNER:
                                if (adPlatform.isSelfAd()) {
                                    adSelfBannerList.add(adPlatform);
                                }
                                break;
                            case ADPlatform.AD_TYPE_GIFT_BOX:
                                if (adPlatform.isSelfAd()) {
                                    adSelfFloatList.add(adPlatform);
                                }
                                break;
                        }
                    }
                }
                if (SZValidatorUtil.isValidList(adSelfBannerList)) {
                    sZXmlUtil.put(AD_LOAD_SELF_BANNER_POLICY, new Gson().toJson(adSelfBannerList));
                } else {
                    sZXmlUtil.remove(AD_LOAD_SELF_BANNER_POLICY);
                }
                if (SZValidatorUtil.isValidList(adSelfFloatList)) {
                    sZXmlUtil.put(AD_LOAD_SELF_FLOAT_POLICY, new Gson().toJson(adSelfFloatList));
                } else {
                    sZXmlUtil.remove(AD_LOAD_SELF_FLOAT_POLICY);
                }
                if (onSplashADLoadListener != null) {
                    onSplashADLoadListener.onFetchAdSuccess(null);
                }
            }

            @Override
            public void onNetError(int errorCode, String errorMsg) {
                SZManager.getInstance().onUMEvent(AD_LOCAL_ERROR_EVENT_ID, getErrorEventMap(AD_PLATFORM_LOCAL, String.valueOf(errorCode), errorMsg));
                SZUtil.log("errorCode:" + errorCode + "|errorMsg:" + errorMsg);
                if (errorCode == 4022044) {
                    sZXmlUtil.remove(AD_LOAD_SPLASH_POLICY);
                    sZXmlUtil.remove(AD_LOAD_NATIVE_POLICY);
                }
                if (onSplashADLoadListener != null) {
                    if (errorCode == 502 || errorCode == ERROR_NET_FAILED) {
                        SZManager.getInstance().onUMEvent(AD_READ_LOCAL_EVENT_ID);
                    }
                    onSplashADLoadListener.onFetchAdError();
                }
            }
        });
    }

    public void getSplash(String channel, String packageName, String version, final OnSplashADLoadListener onSplashADLoadListener) {
        SZRetrofitManager.getInstance().request(getADApiService().getAd(channel, packageName, version, "ALL", deviceId), TAG_SPLASH, new SZRetrofitResponseListener.SimpleSZRetrofitResponseListener() {
            @Override
            public void onSuccess(String data) {
                List<ADPlatform> adPlatformList = new Gson().fromJson(data, new TypeToken<List<ADPlatform>>() {
                }.getType());

                List<ADPlatform> adSplashList = new ArrayList<>();
                List<ADPlatform> adNativeList = new ArrayList<>();
                List<ADPlatform> adSelfBannerList = new ArrayList<>();
                List<ADPlatform> adSelfFloatList = new ArrayList<>();
                List<ADPlatform> adInteractionList = new ArrayList<>();
                if (SZValidatorUtil.isValidList(adPlatformList)) {
                    for (ADPlatform adPlatform : adPlatformList) {
                        switch (adPlatform.getAdType()) {
                            case ADPlatform.AD_TYPE_SPLASH:
                                adSplashList.add(adPlatform);
                                break;
                            case ADPlatform.AD_TYPE_NATIVE:
                                adNativeList.add(adPlatform);
                                break;
                            case ADPlatform.AD_TYPE_BANNER:
                                if (adPlatform.isSelfAd()) {
                                    adSelfBannerList.add(adPlatform);
                                }
                                break;
                            case ADPlatform.AD_TYPE_GIFT_BOX:
                                if (adPlatform.isSelfAd()) {
                                    adSelfFloatList.add(adPlatform);
                                }
                                break;
                            case ADPlatform.AD_TYPE_INTERACTION:
                                adInteractionList.add(adPlatform);
                                break;
                        }
                    }
                }
                String adShowCompany = getAdShownCompany();

                try {
                    if (isSwitchModeAd(adNativeList)) {
                        List<ADPlatform> adNativeSwitchList = getShowPlatform(adNativeList, adShowCompany);
                        sZXmlUtil.put(AD_LOAD_NATIVE_POLICY, new Gson().toJson(adNativeSwitchList));
                    } else {
                        sZXmlUtil.put(AD_LOAD_NATIVE_POLICY, new Gson().toJson(adNativeList));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (SZValidatorUtil.isValidList(adSelfBannerList)) {
                    sZXmlUtil.put(AD_LOAD_SELF_BANNER_POLICY, new Gson().toJson(adSelfBannerList));
                } else {
                    sZXmlUtil.remove(AD_LOAD_SELF_BANNER_POLICY);
                }
                if (SZValidatorUtil.isValidList(adSelfFloatList)) {
                    sZXmlUtil.put(AD_LOAD_SELF_FLOAT_POLICY, new Gson().toJson(adSelfFloatList));
                } else {
                    sZXmlUtil.remove(AD_LOAD_SELF_FLOAT_POLICY);
                }
                if (SZValidatorUtil.isValidList(adInteractionList)) {
                    sZXmlUtil.put(AD_LOAD_INTERACTION_POLICY, new Gson().toJson(adInteractionList));
                } else {
                    sZXmlUtil.remove(AD_LOAD_INTERACTION_POLICY);
                }

                if (isSwitchModeAd(adSplashList)) {
                    List<ADPlatform> adSplashSwitchList = getShowPlatform(adSplashList, adShowCompany);
                    sZXmlUtil.put(AD_LOAD_SPLASH_POLICY, new Gson().toJson(adSplashSwitchList));
                    if (onSplashADLoadListener != null) {
                        onSplashADLoadListener.onFetchAdSuccess(adSplashSwitchList);
                    }
                } else {
                    removeAdShownCompany();
                    sZXmlUtil.put(AD_LOAD_SPLASH_POLICY, new Gson().toJson(adSplashList));
                    if (onSplashADLoadListener != null) {
                        onSplashADLoadListener.onFetchAdSuccess(adSplashList);
                    }
                }
            }

            @Override
            public void onNetError(int errorCode, String errorMsg) {
                SZManager.getInstance().onUMEvent(AD_LOCAL_ERROR_EVENT_ID, getErrorEventMap(AD_PLATFORM_LOCAL, String.valueOf(errorCode), errorMsg));
                SZUtil.log("errorCode:" + errorCode + "|errorMsg:" + errorMsg);
                if (errorCode == 4022044) {
                    sZXmlUtil.remove(AD_LOAD_SPLASH_POLICY);
                    sZXmlUtil.remove(AD_LOAD_NATIVE_POLICY);
                }
                if (onSplashADLoadListener != null) {
                    if (errorCode == 502 || errorCode == ERROR_NET_FAILED) {
                        SZManager.getInstance().onUMEvent(AD_READ_LOCAL_EVENT_ID);
                        String data = sZXmlUtil.getString(AD_LOAD_SPLASH_POLICY);
                        if (data != null && !data.equals("")) {
                            try {
                                List<ADPlatform> adPlatformList = new Gson().fromJson(data, new TypeToken<List<ADPlatform>>() {
                                }.getType());
                                if (isSwitchModeAd(adPlatformList)) {
                                    List<ADPlatform> adSplashSwitchList = getShowPlatform(adPlatformList, getAdShownCompany());
                                    onSplashADLoadListener.onFetchAdSuccess(adSplashSwitchList);
                                } else {
                                    onSplashADLoadListener.onFetchAdSuccess(adPlatformList);
                                }
                                return;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    onSplashADLoadListener.onFetchAdError();
                }
            }
        });
    }

    private boolean isSwitchModeAd(List<ADPlatform> adPlatformList) {
        if (SZValidatorUtil.isValidList(adPlatformList)) {
            for (ADPlatform adPlatform : adPlatformList) {
                if (isSwitchModeAd(adPlatform)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isSwitchModeAd(ADPlatform adPlatform) {
        if (adPlatform == null || adPlatform.getAdShowTypeInfo() == null || adPlatform.getAdShowTypeInfo().getShowType() == null) {
            return false;
        }
        return "1".equals(adPlatform.getAdShowTypeInfo().getShowType());
    }

    private List<ADPlatform> getShowPlatform(List<ADPlatform> adPlatformList, String adShowCompany) {
        if (!TextUtils.isEmpty(adShowCompany)) {
            List<ADPlatform> adPlatformSortList = new ArrayList<>();
            if (SZValidatorUtil.isValidList(adPlatformList)) {
                for (ADPlatform adPlatform : adPlatformList) {
                    if (!adShowCompany.equalsIgnoreCase(adPlatform.getAdSupportType())) {
                        adPlatformSortList.add(adPlatform);
                        adPlatformList.remove(adPlatform);
                        break;
                    }
                }
                if (SZValidatorUtil.isValidList(adPlatformList)) {
                    adPlatformSortList.add(adPlatformList.get(0));
                }
            }
            return adPlatformSortList;
        }
        return adPlatformList;
    }

    public List<ADPlatform> getInteractionAdList() {
        List<ADPlatform> adPlatformList = null;
        String interaction = sZXmlUtil.getString(AD_LOAD_INTERACTION_POLICY);
        if (SZValidatorUtil.isValidString(interaction)) {
            adPlatformList = new Gson().fromJson(interaction, new TypeToken<List<ADPlatform>>() {
            }.getType());
        }
        return adPlatformList;
    }

    public List<MaterialsInfo> getSelfBannerList() {
        List<MaterialsInfo> materialsInfoList = new ArrayList<>();
        try {
            String banner = sZXmlUtil.getString(AD_LOAD_SELF_BANNER_POLICY);
            if (SZValidatorUtil.isValidString(banner)) {
                List<ADPlatform> bannerList = new Gson().fromJson(banner, new TypeToken<List<ADPlatform>>() {
                }.getType());
                if (bannerList != null) {
                    for (ADPlatform adPlatform : bannerList) {
                        materialsInfoList.add(adPlatform.getMaterialsInfo());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return materialsInfoList;
    }

    public MaterialsInfo getSelfFloat() {
        try {
            String giftBox = sZXmlUtil.getString(AD_LOAD_SELF_FLOAT_POLICY);
            if (SZValidatorUtil.isValidString(giftBox)) {
                List<ADPlatform> floatList = new Gson().fromJson(giftBox, new TypeToken<List<ADPlatform>>() {
                }.getType());
                if (floatList != null) {
                    for (ADPlatform adPlatform : floatList) {
                        return adPlatform.getMaterialsInfo();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Map<String, String> getErrorEventMap(String platform, String errorCode, String errorMsg) {
        Map<String, String> params = new HashMap<>();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ERROR_MSG, errorMsg);
            jsonObject.put(ERROR_CODE, errorCode);
            params.put(platform, jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return params;
    }

    public interface OnSplashADLoadListener {
        void onFetchAdSuccess(List<ADPlatform> adPlatformList);

        void onFetchAdError();
    }

    private static int getGDTChannelCode() {
        String channel = SZUtil.getChannel(SZManager.getInstance().getContext());
        int channelCode = 999;
//        1	百度
//        2	头条
//        3	优量汇
//        4	搜狗
//        5	其他网盟
//        6	oppo
//        7	vivo
//        8	华为
//        9	应用宝
//        10	小米
//        11	金立
//        12	百度手机助手
//        13	魅族
//        14	AppStore
//        999	其他
        if (SZValidatorUtil.isValidString(channel)) {
            switch (channel) {
                case "huawei":
                    channelCode = 8;
                    break;
                case "oppo":
                    channelCode = 6;
                    break;
                case "vivo":
                    channelCode = 7;
                    break;
                case "xiaomi":
                    channelCode = 10;
                    break;
                case "baidu":
                    channelCode = 1;
                    break;
                case "tencent":
                    channelCode = 9;
                    break;
                case "meizu":
                    channelCode = 13;
                    break;
                case "wandoujia":
                case "qihu360":
                    channelCode = 5;
                    break;
                case "sougou":
                    channelCode = 4;
                    break;
                case "toutiao":
                    channelCode = 2;
                    break;
                case "gdt":
                    channelCode = 3;
                    break;
            }
        }
        return channelCode;
    }

    public OnAdInitDoneListener getOnAdInitDoneListener() {
        return onAdInitDoneListener;
    }

    public void setOnAdInitDoneListener(OnAdInitDoneListener onAdInitDoneListener) {
        this.onAdInitDoneListener = onAdInitDoneListener;
    }

    public interface OnAdInitDoneListener {
        void onTTAdInitDone(boolean isSuccess);
    }
}
